import Cookies from "js-cookie";
import global_ from "../global.config";
import Qs from "qs";
export default {
  // 验证手机号码合法性
  isMobile: function(mobile) {
    return /^1+\d{10}$/.test(String(mobile).replace(/^0+/g, ""));
  },
  getTime: function(time) {
    let date = new Date(time);
    let m = date.getMonth() + 1;
    m <= 9 ? (m = "0" + m) : m;
    let d = date.getDate();
    d <= 9 ? (d = "0" + d) : d;
    return date.getFullYear() + "-" + m + "-" + d;
  },
  getFullTime: function(time) {
    let date = new Date(time);
    let m = date.getMonth() + 1;
    m <= 9 ? (m = "0" + m) : m;
    let d = date.getDate();
    d <= 9 ? (d = "0" + d) : d;
    let h = date.getHours();
    h <= 9 ? (h = "0" + h) : h;
    let m2 = date.getMinutes();
    m2 <= 9 ? (m2 = "0" + m2) : m2;
    let s = date.getSeconds();
    s <= 9 ? (s = "0" + s) : s;
    return (
      date.getFullYear() + "-" + m + "-" + d + " " + h + ":" + m2 + ":" + s
    );
  },
  getFullTimeHm: function(time) {
    let date = new Date(time);
    let m = date.getMonth() + 1;
    // m <= 9 ? (m = "0" + m) : m;
    let d = date.getDate();
    // d <= 9 ? (d = "0" + d) : d;
    let h = date.getHours();
    h <= 9 ? (h = "0" + h) : h;
    let m2 = date.getMinutes();
    m2 <= 9 ? (m2 = "0" + m2) : m2;
    return date.getFullYear() + "年" + m + "月" + d + "日 " + h + ":" + m2;
  },
  initCookies: function(query) {
    // let query = Qs.parse(location.search.substring(1));
    let baseUrl = `${location.protocol}//${location.host}${location.pathname}`;
    if (query.j) {
      let params = JSON.parse(query.j);
      global_.paramKeys.forEach(name => {
        if (name in params) {
          Cookies.set(name, params[name], { expires: 30 });
        }
      });
      delete query.j;
      setTimeout(function() {
        if (Qs.stringify(query)) {
          window.location.href = `${baseUrl}?${Qs.stringify(query)}`;
        } else {
          window.location.href = baseUrl;
        }
      }, 100);
    } else if (query.cmd && query.cmd === "clean") {
      global_.paramKeys.forEach(name => {
        Cookies.remove(name);
      });
      delete query.cmd;
      let url = Qs.stringify(query)
        ? `${baseUrl}?${Qs.stringify(query)}`
        : baseUrl;
      window.location.href = url;
    } else if (query.fake) {
      global_.paramKeys.forEach(name => {
        if (global_.FAKE_DATA[query.fake]) {
          Cookies.set(name, global_.FAKE_DATA[query.fake][name], {
            expires: 30
          });
        }
      });
    }
  },
  needsAuth: function(type, callback) {
    if (Cookies.get("openid") && Cookies.get("passport")) {
      if (Cookies.get("passport") === "null") {
        global_.paramKeys.forEach(name => {
          Cookies.remove(name);
        });
        window.location.reload();
      } else {
        callback();
      }
    } else {
      let query = Qs.parse(location.search.substring(1));
      delete query.cmd;
      delete query.j;
      let url = `${location.protocol}//${location.host}${
        location.pathname
      }?${Qs.stringify(query)}`;
      Cookies.set("appid", global_.APPID, { expires: 30 });
      this.parseOauthUrl(url, type);
    }
  },
  parseOauthUrl: function(url, type) {
    // alert(type)
    let redirectUrl = url || location.href;
    let scope = type == 1 ? "snsapi_userinfo" : "snsapi_base";
    // alert(scope)
    Cookies.set(`${global_.APPID}-oauth-state`, redirectUrl, { expires: 30 });
    let auth_url = global_.OAUTH_URL.replace(
      /\{appid\}/g,
      encodeURIComponent(global_.APPID)
    )
      .replace(
        "{state}",
        encodeURIComponent(
          `${location.protocol}//${location.host}${
            global_.GLOBAL_BASE_PATH
          }/redirect`
        )
      )
      .replace("{scope}", scope);
    // alert(auth_url);
    window.location.href = auth_url;
  },
  uploadFile: function(params, file, callback) {
    const OSS = require("ali-oss");
    let client = new OSS({
      accessKeyId: params.credentials.accessKeyId,
      accessKeySecret: params.credentials.accessKeySecret,
      stsToken: params.credentials.securityToken,
      endpoint: params.endpoint,
      bucket: params.bucket
    });
    let suffix = file.name.split(".").pop();
    let storeAs = `${params.dir}/${global_.APPID}/${Date.parse(
      new Date()
    )}-${Math.floor(Math.random() * 100 + 1)}.${suffix}`;
    let url = `${params.host}/${storeAs}`;
    client
      .multipartUpload(storeAs, file, {})
      .then(results => {
        callback(url);
      })
      .catch(err => {
        // console.log(err);
      });
  },
  textMatch: function(word1, word2, rate) {
    // try {
    let command = word1
      .toString()
      .trim()
      .replace(/[^\u4e00-\u9fa5a-zA-Z\d]+/g, "");
    let word = word2
      .toString()
      .trim()
      .replace(/[^\u4e00-\u9fa5a-zA-Z\d]+/g, "");
    if (command.trim().length != word.trim().length) {
      return false;
    } else {
      let rightCount = 0;
      for (let i = 0; i < command.length; i++) {
        if (word[i] == command[i]) {
          rightCount += 1;
        }
      }
      return rightCount / command.length > rate;
    }
    // } catch (e) {
    // }
  },
  browser: {
    info: navigator.appVersion,
    versions: (function() {
      let u = navigator.userAgent;
      return {
        trident: u.indexOf("Trident") > -1,
        presto: u.indexOf("Presto") > -1,
        webKit: u.indexOf("AppleWebKit") > -1,
        gecko: u.indexOf("Gecko") > -1 && u.indexOf("KHTML") == -1,
        mobile: !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/),
        ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
        android: u.indexOf("Android") > -1 || u.indexOf("Linux") > -1,
        iPhone: u.indexOf("iPhone") > -1 || u.indexOf("Mac") > -1,
        iPad: u.indexOf("iPad") > -1,
        webApp: u.indexOf("Safari") == -1,
        wx: u.toLowerCase().match(/MicroMessenger/i) == "micromessenger"
      };
    })()
  }
};
